//
//  AFSoundRecord.m
//  AFSoundManager-Demo
//
//  Created by Alvaro Franco on 10/02/15.
//  Copyright (c) 2015 AlvaroFranco. All rights reserved.
//

#import "AFSoundRecord.h"
#import <AVFoundation/AVFoundation.h>


@interface AFSoundRecord () <AVAudioRecorderDelegate>

@property (nonatomic, strong) AVAudioRecorder *recorder;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) NSTimeInterval timeInterval;

@end

@implementation AFSoundRecord

- (instancetype)initWithFilePath:(NSString *)filePath {

    self = [super init];
    if (self) {
        _filePath = filePath;

        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if (session == nil)
            NSLog(@"Error creating session: %@", [sessionError description]);
        else
            [session setActive:YES error:nil];

        _recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:filePath] settings:[self audioSetting] error:nil];
        _recorder.delegate = self;
        [_recorder prepareToRecord];

        //设置定时检测
        if (_timer) {
            [_timer invalidate];
            _timer = nil;
        }
        _timeInterval = 0;
        _timer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];

    }

    return self;
}

- (void)detectionVoice {
    [_recorder updateMeters];
    _timeInterval = _recorder.currentTime;
    if (_progress) {
        _progress(_timeInterval);
    }
}

- (NSDictionary *)audioSetting {
    // 设置录音和压缩参数
    // record settings kAudioFormatMPEG4AAC kAudioFormatMPEG4AAC_LD kAudioFormatMPEG4AAC_ELD
    NSMutableDictionary *settings = [[NSMutableDictionary alloc] init];
    // 声音的编码格式
    [settings setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    // 声音的采样率8000次
    [settings setValue:[NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
    // 声音的使用声道（单声道）
    [settings setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    // 声音的位深度
    [settings setValue:[NSNumber numberWithInt:8] forKey:AVLinearPCMBitDepthKey];
    [settings setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [settings setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
    // Encoder
    // 编码器的采样率
    [settings setValue:[NSNumber numberWithInt:12000] forKey:AVEncoderBitRateKey];
    // 编码器的位深度
    [settings setValue:[NSNumber numberWithInt:8] forKey:AVEncoderBitDepthHintKey];
    // 编码器的声道采样率
    [settings setValue:[NSNumber numberWithInt:8] forKey:AVEncoderBitRatePerChannelKey];
    // 编码器的编码质量
    [settings setValue:AVAudioQualityMin forKey:AVEncoderAudioQualityKey];

    return settings;
}

- (float)currentTime {
    return _timeInterval;
}

- (void)startRecording {

    [_recorder record];
}

- (void)startRecording:(NSTimeInterval)duration {
    [_recorder recordForDuration:duration];
}

- (void)saveRecording {

    [_recorder stop];
}

- (void)saveRecordingComplete:(void (^)(BOOL flag))complete {
    _recordComplete = complete;
    [_recorder stop];
}

- (void)cancelCurrentRecording {
    [_recorder stop];
    [_recorder deleteRecording];
}

- (void)stopRecording {
    [_recorder stop];
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    if (_recordComplete) {
        _recordComplete(flag);
    }
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

@end
